import React from "react";
import ReactDOM from "react-dom";

// class Demo extends React.Component {
//   state = { count: 0 };
//   add = () => {
//     this.setState((state) => ({ count: state.count + 1 }));
//   };
//   componentDidMount(){
//       this.timer = setInterval(()=>{
//         this.setState(state=>({count:state.count+1}))
//       },1000)
//   }
//   componentWillUnmount(){
//       clearInterval(this.timer)
//   }
//   unmount = ()=>{
//     ReactDOM.unmountComponentAtNode(document.getElementById('root'))
//   }
//   myRef = React.createRef()
//   show = ()=>{
//       alert(this.myRef.current.value)
//   }
//   render() {
//     return (
//       <div>
//           <input type="text" ref={this.myRef}/>
//         <h2>累加之和为：{this.state.count}</h2>
//         <button onClick={this.add}>点我+1</button>
//         <button onClick={this.unmount}>卸载组件</button>
//         <button onClick={this.show}>提示数据</button>
//       </div>
//     );
//   }
// }

function Demo() {
  console.log("Demo");
  const [count, setCount] = React.useState(0);
  const [name, setName] = React.useState("tom");
  const myRef = React.useRef();

  //加的回调
  function add() {
    // setCount(count+1) //第一种写法
    setCount((count) => count + 1);
  }

  function changeName() {
    setName("jack");
  }

  React.useEffect(() => {
    console.log("@@");
    let timer = setInterval(() => {
      setCount((count) => count + 1);
    }, 1000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  //卸载组件的回调
  function unmount() {
    ReactDOM.unmountComponentAtNode(document.getElementById("root"));
  }

  function show(){
    alert(myRef.current.value);
  }

  return (
    <div>
      <input type="text" ref={myRef} />
      <h2>当前求和为：{count}</h2>
      <h2>我的名字是：{name}</h2>
      <button onClick={add}>点我+1</button>
      <button onClick={changeName}>点我修改名字</button>
      <button onClick={unmount}>卸载组件</button>
      <button onClick={show}>提示数据</button>
    </div>
  );
}

export default Demo;
